//
//  HomeViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/9/14.
//  Copyright (c) 2015年 zhixiao. All rights reserved.
//

import UIKit

class HomeViewController: BaseViewController {
    var scrollView:UIScrollView!
    var imageScrollView:UIScrollView!
    var pageControl:UIPageControl!
     var cartTable:UITableView!
    var menuView:UIView!
    var topView:UIView!
    var searchBar:UISearchBar!
    var searchBtn:UIButton!
    var infoBtn:UIButton!
    var bannerArray:[BannerObj] = []
    var RoundArray:[BannerObj] = []
    var homeCategory:[homeCategoryObj] = []
    let scrollHeight = windowHeight-49-20
    var autoScrollTimer:NSTimer!
    override func viewDidLoad() {
        super.viewDidLoad()
        let redView = UIView(frame: CGRectMake(0, 0, view.bounds.size.width, 20))
        redView.backgroundColor = commonRedColor
        view.addSubview(redView)
               // Do any additional setup after loading the view.
        scrollView = UIScrollView(frame: CGRectMake(0, 20, windowWidth, scrollHeight))
        scrollView.backgroundColor = commonBackgoundColor
        scrollView.delegate = self
        view.addSubview(scrollView)
        self.setupTopView()
        
        
        searchBtn = UIButton(frame: CGRectMake(view.bounds.width - 80, 25, 30, 30))
        searchBtn.addTarget(self, action: "gosearch", forControlEvents: UIControlEvents.TouchUpInside)
        searchBtn.setBackgroundImage(UIImage(named: "search"), forState: UIControlState.Normal)
        view.addSubview(searchBtn)
        searchBtn.hidden = true
        
        infoBtn = UIButton(frame: CGRectMake(view.bounds.width - 40, 25, 30, 30))
        infoBtn.addTarget(self, action: "showInfo", forControlEvents: UIControlEvents.TouchUpInside)
        infoBtn.setBackgroundImage(UIImage(named: "mail"), forState: UIControlState.Normal)
        view.addSubview(infoBtn)
        infoBtn.hidden = true
        
        menuView = UIView(frame: CGRectMake(0, 160, view.bounds.size.width, 70))
        menuView.backgroundColor = UIColor.whiteColor()
        scrollView.addSubview(menuView)

//        self.layoutTopScrollView()
        self.queryBanners()
        self.queryRounds()
        self.queryHomeCategory()
    }
    
    func queryBanners()->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        request.requestStart("/flashSale/getBanners", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                }
                if let array = dic?.pareseDataToBannerArray(){
                    self.bannerArray = array
                    dispatch_async(dispatch_get_main_queue()){
                        self.layoutTopScrollView()
                    }
                }
                dispatch_async(dispatch_get_main_queue()){
                }
            }
            else{
                self.showTips("加载失败")
            }
        })
        self.showProcess("加载中...")
    }
    func queryRounds()->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        request.requestStart("/flashSale/getRounds", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                }
                if let array = dic?.pareseDataToBannerArray(){
                    self.RoundArray = array
                    dispatch_async(dispatch_get_main_queue()){
                        self.setupMenuView()
                    }
                }
                dispatch_async(dispatch_get_main_queue()){
                }
            }
            else{
                self.showTips("加载失败")
            }
        })
        self.showProcess("加载中...")
    }
    func queryHomeCategory()->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        request.requestStart("/category/getHomeCategory", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                }
                if let array = dic?.pareseDataToHomeCategoryArray(){
                    self.homeCategory = array
                    dispatch_async(dispatch_get_main_queue()){
                        self.createTableView()
                    }
                }
                dispatch_async(dispatch_get_main_queue()){
                }
            }
            else{
                self.showTips("加载失败")
            }
        })
        self.showProcess("加载中...")
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBarHidden = true
    }
    func setupTopView(){
        //237,63,88
        topView = UIView(frame: CGRectMake(0, 0, view.bounds.size.width, topViewHeight))
        topView.backgroundColor = UIColor.clearColor()
        view.addSubview(topView)
        
        searchBar = UISearchBar(frame: CGRectMake(10, 22, view.bounds.size.width-10-40, 40))
        searchBar.searchBarStyle = UISearchBarStyle.Prominent
        searchBar.placeholder = "女神新装"
        searchBar.delegate = self
        if let aview = searchBar.subviews[0] as? UIView{
            if aview.subviews.count>0{
                aview.subviews[0].removeFromSuperview()
            }
        }
        topView.addSubview(searchBar)
        
        let messageBtn = MyButton(frame: CGRectMake(0, 0, 40, 34))
        messageBtn.imageSize = CGSizeMake(16, 16)
        messageBtn.center = CGPointMake(topView.bounds.size.width - messageBtn.frame.size.width/2.0-5, searchBar.center.y)
//        messageBtn.alwaysUnhightlighted = false
        messageBtn.setTitle("消息", forState: UIControlState.Normal)
        messageBtn.titleLabel?.font = UIFont.boldSystemFontOfSize(11)
        messageBtn.titleLabel?.textAlignment = NSTextAlignment.Center
        messageBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        messageBtn.setImage(UIImage(named:"chat-"), forState: UIControlState.Normal)
        messageBtn.addTarget(self, action: "showInfo", forControlEvents: UIControlEvents.TouchUpInside)
        messageBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
        topView.addSubview(messageBtn)
    }
    func showInfo(){
        let ctl = MessageViewController()
        self.navigationController?.pushViewController(ctl, animated: true)
    }
    func setupMenuView()->Void{
        if RoundArray.count == 0{
            return
        }
        let buttonWidth = windowWidth/CGFloat(RoundArray.count)
        let buttonHeight:CGFloat = 60
        for i in 0..<RoundArray.count{
            let button = TabButton(frame: CGRectMake(buttonWidth*CGFloat(i), 5, buttonWidth, buttonHeight))
            
            button.setTitle(RoundArray[i].title, forState: UIControlState.Normal)
            button.titleLabel?.font = UIFont.systemFontOfSize(11)
//            button.titleLabel?.textAlignment = NSTextAlignment.Center
//            button.setTitleColor(UIColor(red: 29.0/255, green: 173.0/255, blue: 248.0/255, alpha: 1.0), forState: UIControlState.Selected)
//            button.setTitleColor(UIColor(red: 128.0/255, green: 128.0/255, blue: 128.0/255, alpha: 1.0), forState: UIControlState.Normal)
//            button.setImage(UIImage(named: imageNomalArray[i]), forState: UIControlState.Normal)
//            button.setImage(UIImage(named: imageSelectArray[i]), forState: UIControlState.Selected)
            let imageView =  XZImageView(frame: CGRectMake(0, 3, button.bounds.size.width, 40))
            imageView.setImageWithUrl(RoundArray[i].imgurl!, defaultImage: nil)
            imageView.contentMode = UIViewContentMode.ScaleAspectFit
            button.addSubview(imageView)
            let lbl = UILabel(frame:CGRectMake(0, CGRectGetMaxY(imageView.frame), button.bounds.size.width, button.bounds.size.height - 40))
            lbl.font = UIFont.systemFontOfSize(11)
            lbl.textAlignment = NSTextAlignment.Center
            lbl.text = RoundArray[i].title
            button.addSubview(lbl)
            button.tag = i
            button.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchDown)
            menuView.addSubview(button)
        }
    }
    func layoutTopScrollView()->Void{
        imageScrollView = UIScrollView(frame: CGRectMake(0, 0, view.bounds.size.width, 150))
        imageScrollView.showsHorizontalScrollIndicator=false
        imageScrollView.showsVerticalScrollIndicator = false
        //        imageScrollView.backgroundColor = UIColor(red: 246/255.0, green: 246/255.0, blue: 246/255.0, alpha: 1.0)
        imageScrollView.backgroundColor = UIColor.whiteColor()
        
        imageScrollView.pagingEnabled = true
        imageScrollView.delegate = self
        imageScrollView.contentSize = CGSizeMake(view.bounds.size.width*3, 150)
        var tapImageView:TapImageView!
//        let imageArray = ["pic1","pic2","pic3"]
        for i in 0..<self.bannerArray.count{
            let originX = CGFloat(i)*view.bounds.size.width
            let obj = self.bannerArray[i]
            tapImageView = TapImageView(frame: CGRectMake(originX, 0, view.bounds.size.width, 150))
            tapImageView.setImageWithUrl(obj.imgurl!, defaultImage: nil)
            tapImageView.contentMode = UIViewContentMode.ScaleToFill
            tapImageView.id = "\(i+1)"
            tapImageView.TapCompelete = {[weak self] id in
                let ctl = HTMLViewController()
                ctl.bannerObj = obj
                ctl.title = obj.title
                self?.navigationController?.pushViewController(ctl, animated: true)
            }
            imageScrollView.addSubview(tapImageView)
        }
        pageControl = UIPageControl()
        pageControl.frame = CGRectMake(0, CGRectGetMaxY(imageScrollView.frame)-30, imageScrollView.bounds.size.width, 30)
        pageControl.numberOfPages = self.bannerArray.count
        pageControl.currentPage = 0
        pageControl.pageIndicatorTintColor = UIColor.blackColor()
        pageControl.currentPageIndicatorTintColor = UIColor.whiteColor()
        pageControl.addTarget(self, action: "pageTurn:", forControlEvents: UIControlEvents.ValueChanged)
        scrollView.addSubview(imageScrollView)
        scrollView.addSubview(pageControl)
        self.startScrollTimer()
    }
    func pageTurn(control:UIPageControl){
        let size = imageScrollView.bounds.size
        let rect = CGRectMake(CGFloat(control.currentPage)*size.width, 0, size.width, size.height)
        imageScrollView.scrollRectToVisible(rect, animated: true)
    }
    func startScrollTimer(){
        autoScrollTimer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: "autoScroll:", userInfo: nil, repeats: true)
        NSRunLoop.currentRunLoop().addTimer(autoScrollTimer, forMode: NSRunLoopCommonModes)
    }
    func stopScrollTimer(){
        autoScrollTimer?.invalidate()
    }
    func autoScroll(aTimer:NSTimer)->Void{
        var index = pageControl.currentPage
        if index == pageControl.numberOfPages-1{
            index = 0
        }
        else{
            index++
        }
        pageControl.currentPage = index
        self.pageTurn(pageControl)
    }
    func createTableView(){
        //        leftTableDataSource.addObjectsFromArray(["热门品牌","食品/保健","美妆个护","母婴用品","服饰鞋包","生活数码"])
        cartTable = UITableView(frame: CGRectMake(0, CGRectGetMaxY(menuView.frame)+10, view.bounds.size.width, 2250), style: UITableViewStyle.Plain)
        cartTable.backgroundColor = UIColor.clearColor()
        cartTable.separatorStyle = UITableViewCellSeparatorStyle.None
        cartTable.showsHorizontalScrollIndicator = false
        cartTable.showsVerticalScrollIndicator = false
        cartTable.dataSource = self
        cartTable.rowHeight = 200.0
        cartTable.delegate = self
        cartTable.scrollEnabled = false
        let nib = UINib(nibName:"GoodsGridCell", bundle:nil)
        cartTable.registerNib(nib,forCellReuseIdentifier:"GoodsGridCellID")
        scrollView.addSubview(cartTable)
        scrollView.contentSize = CGSizeMake(scrollView.bounds.size.width, CGRectGetMaxY(cartTable.frame))
    }
    func buttonClick(button:UIButton){
        print(button.tag)
        let ctl = HTMLViewController()
        ctl.bannerObj = self.RoundArray[button.tag]
        ctl.title = ctl.bannerObj!.title
        self.navigationController?.pushViewController(ctl, animated: true)
    }
    func gosearch(){
        let ctl = SearchViewController()
        self.navigationController?.pushViewController(ctl, animated: true)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension HomeViewController:UITableViewDataSource,UITableViewDelegate{
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return self.homeCategory.count
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
//        return self.dataSource!.items!.count
        return 2
    }
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        return 45
    }
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{
        let headView = NSBundle.mainBundle().loadNibNamed("HomeCellHeaderView", owner: nil, options: nil)[0] as! HomeCellHeaderView
        headView.headImageView.image = UIImage(named: "food_icon2")
//        headView.name.text = categoryArray[section]
//        headView.info1.text = info1Array[section]
//        headView.info2.text = info2Array[section]
        let obj = self.homeCategory[section]
        headView.name.text = obj.name
        headView.info1.text = obj.rootName?[0]["subname"] as? String
        headView.info2.text = obj.rootName?[1]["subname"] as? String
        headView.section = section
        headView.enterButtonClickHandle = {[weak self] section in
            if let nav = GlobalDataHelper.instance.tabCtl?.viewControllers?[1] as? UINavigationController{
                if let ctl = nav.viewControllers[0] as? CategoryViewController {
                    let path = NSIndexPath(forRow: section, inSection: 0)
                    ctl.selectIndexOfLeftTable = path
                    ctl.selectMenuWithIndexPath(path)
                }
            }
            GlobalDataHelper.instance.tabCtl?.setSelectCtl(1)
        }
        return headView
        
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell{
        let cell = tableView.dequeueReusableCellWithIdentifier("GoodsGridCellID", forIndexPath: indexPath) as! GoodsGridCell
        //        cell.wineImageView.image = imageArray[indexPath.row].0
        cell.indexPath = indexPath
        var obj1,obj2:GoodDetailItem?
        if let dataArray = self.homeCategory[indexPath.section].product{
            obj1 = dataArray[indexPath.row*2]
            if indexPath.row*2+1 < dataArray.count{
                obj2 = dataArray[indexPath.row*2+1]
            }
        }
        cell.imageView1.setImageWithUrl(obj1!.image!, defaultImage:nil)
        cell.name1.text = obj1?.name
        cell.price1.text = "¥"+obj1!.price!
        if obj2 == nil{
            cell.cell2.hidden = true
        }
        else{
            cell.imageView2.setImageWithUrl(obj2!.image!, defaultImage:nil)
            cell.name2.text = obj2?.name
            cell.price2.text = "¥"+obj2!.price!
        }
        
        cell.btnHandle = {[weak self] indexPath,buttonIndex in
            print("第\(indexPath!.row)个cell,第\(buttonIndex)个按钮")
            //                                self?.selectObj = self?.rightMenuSource[indexPath!.row*2+buttonIndex]
            let ctl = GoodsDetailViewController()
            if let dataArray = self?.homeCategory[indexPath!.section].product{
                let obj:GoodDetailItem = (dataArray[indexPath!.row*2+buttonIndex])
                ctl.goodsID = obj.id
            }
            ctl.hidesBottomBarWhenPushed = true
            self?.navigationController?.pushViewController(ctl, animated: true)
        }
        return cell
    }
}
extension HomeViewController:UIScrollViewDelegate{
    func scrollViewDidScroll(scrollView: UIScrollView){
        if scrollView == self.scrollView{
            if scrollView.contentOffset.y > self.topView.bounds.size.height{
                topView.hidden = true
                searchBtn.hidden = false
                infoBtn.hidden = false
            }
            else{
                topView.hidden = false
                searchBtn.hidden = true
                infoBtn.hidden = true
            }
        }
    }
    func scrollViewWillBeginDragging(scrollView: UIScrollView){
        if scrollView == self.imageScrollView{
            self.stopScrollTimer()
        }
    }
    func scrollViewWillBeginDecelerating(scrollView: UIScrollView){
        if scrollView == self.imageScrollView{
            self.stopScrollTimer()
        }
    }
    func scrollViewDidEndDecelerating(scrollView: UIScrollView){
        if scrollView == self.imageScrollView{
            let point = scrollView.contentOffset
            let rect = self.imageScrollView.bounds
            pageControl.currentPage = Int(point.x/rect.size.width)
            self.startScrollTimer()
        }
    }
}
extension HomeViewController:UISearchBarDelegate{
//    func searchBarSearchButtonClicked(searchBar: UISearchBar){
//        searchBar.resignFirstResponder()
//        let ctl = SearchViewController()
//        self.navigationController?.pushViewController(ctl, animated: true)
//    }
    func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool{
        searchBar.resignFirstResponder()
        let ctl = SearchViewController()
        self.navigationController?.pushViewController(ctl, animated: true)
        return false
    }
}